package xyz.lisys.action;

import com.opensymphony.xwork2.ActionSupport;
import ognl.Ognl;
import ognl.OgnlException;
import org.springframework.context.annotation.Scope;
import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


@Controller("demoAction")
@Scope("prototype")
public class DemoAction extends ActionSupport {
    public String view() {
        expressionSpel();
        expressionOgnl();
        return SUCCESS;
    }

    // Spring SpeL表达式
    public void expressionSpel() {
        String elExpress = "${value1==value2}";
        Map<String, Object> contextValueMap = new HashMap<>();
        contextValueMap.put("value1", 1);
        contextValueMap.put("value2", 1);

        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();

        context.setPropertyAccessors(Collections.singletonList(new MapAccessor()));
        context.setVariables(contextValueMap);

        SpelExpression expression = (SpelExpression) parser.parseExpression(
                elExpress, new TemplateParserContext("${", "}")
        );
        expression.setEvaluationContext(context);

        System.out.println(expression.getValue(contextValueMap, boolean.class));
    }

    // Struts2 Ognl表达式
    public void expressionOgnl() {
        String elExpress = "value1==value2";
        Map<String, Object> contextValueMap = new HashMap<>();
        contextValueMap.put("value1", 1);
        contextValueMap.put("value2", 1);

        // OgnlContext context = (OgnlContext) ActionContext.getContext().getValueStack().getContext();
        try {
            System.out.println(Ognl.getValue(
                    Ognl.parseExpression(elExpress),
                    Ognl.createDefaultContext(contextValueMap)
            ));
        } catch (OgnlException e) {
            throw new RuntimeException(e);
        }
    }
}
